<?php

namespace app\admin\controller;

use app\admin\model\TaskSettle;
use app\admin\model\TasksService;
use app\admin\model\CommissionLog;
use app\common\controller\Backend;
use app\common\library\Export;
use app\common\model\TaskAction;
use app\common\model\TaskItem;
use think\Db;
use think\exception\DbException;
use think\exception\ValidateException;
use think\Hook;
use think\Loader;
use think\response\Json;
use think\exception\PDOException;
use think\Exception;

/**
 * 任务管理
 *
 * @icon fa fa-tasks
 */
class Tasks extends Backend
{

    /**
     * Tasks模型对象
     * @var \app\admin\model\Tasks
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Tasks;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("currFlowList", $this->model->getCurrFlowList());
        $this->view->assign("takeStatusList", $this->model->getTakeStatusList());
        $this->view->assign("pickStatusList", $this->model->getPickStatusList());
        $this->view->assign("serviceStatusList", $this->model->getServiceStatusList());
        $this->view->assign("returnStatusList", $this->model->getReturnStatusList());
        $this->view->assign("returnTypeList", \app\admin\model\ReturnType::getReturnTypeList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    //获取 range
    public function get_range()
    {
        $list = [
            [
                'label'     => '半小时内',
                'value'     => '1800',
            ], [
                'label'     => '一小时内',
                'value'     => '3600',
            ], [
                'label'     => '两小时内',
                'value'     => '7200',
            ], [
                'label'     => '三小时内',
                'value'     => '10800',
            ], [
                'label'     => '一天内',
                'value'     => '86400',
            ], [
                'label'     => '两天内',
                'value'     => '17800',
            ], [
                'label'     => '超出两天',
                'value'     => 'range_more',
            ],
        ];
        $total = count($list);
        return json(['total' => $total, 'list' => $list]);
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with('user,pick,return,insurance_company,settle')
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list->items() as &$item){
            $item['service_item'] = TasksService::getItem($item->id);
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    //任务时效
    public function range()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with('user,pick,return,insurance_company')
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 结算
     *
     * @return string
     * @throws \think\Exception
     */
    public function settle($ids=null)
    {
        if (false == $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        if (!is_numeric($params['price'])) {
            $this->error('金额不正确');
        }
        $row = $this->model->where('id', $ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row->settle_status == 1){
            $this->error('该任务已结算');
        }
        $params['task_id'] = $ids;
        $result = false;
        Db::startTrans();
        try {
            //结算
            $row->status = 7;
            $row->settle_status = 1;
            $row->save();
            //添加关联表
            $result = TaskSettle::create($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }


    /**
     * 详情
     */
    public function detail($ids)
    {
        $row = $this->model->with('user,pick,return,insurance_company')->where(['id' => $ids])->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isAjax()) {
            $this->success("Ajax请求成功", null, ['id' => $ids]);
        }
        //任务详情
        $this->view->assign("row", $row->toArray());
        //维修明细
        $this->view->assign("taskService", TasksService::getTasksService($ids));
        //任务提成
        $this->view->assign('commissionLog',CommissionLog::getTasksLog($ids));
        //结算信息
        $this->view->assign('settle',TaskSettle::getSettle($ids));
        return $this->view->fetch();
    }

    /*
     * 导出
     */
    public function export()
    {
        if ($this->request->isPost()) {
            $ids = $this->request->post('ids');

            // 获取请求参数（支持筛选条件）
            $params = $this->request->param();
            $filter = json_decode($params['filter'] ?? '{}', true);
            $op = json_decode($params['op'] ?? '{}', true);

            if ($ids != 'all') {
                $dataList = $this->model->with('user,pick,return,insurance_company')->whereIn('id', $ids)->select();
            }else{
                $dataList = $this->model->with('user,pick,return,insurance_company')->where($filter)->select();
            }

            $expCellName = [
                'id'                            => 'Id',
                'order_sn'                      => '订单编号',
                'user_nickname'                 => '发起人',
                'date'                          => '开单日期',
                'models'                        => '车辆型号',
                'car_number'                    => '车牌号',
                'province_name'                 => '省',
                'city_name'                     => '市',
                'area_name'                     => '区',
                'address'                       => '取件地址',
                'name_4s'                       => '4s店名称',
                'insurance_company'             => '保险公司',
                'receptionist'                  => '业务接待员',
                'pick_nickname'                 => '取件人',
                'sure_name'                     => '定损人',
                'return_name'                   => '回款方式',
                'price'                         => '预估金额',
                'status'                        => '状态',
                'remark'                        => '备注',
                'images'                        => '修复前图片',
                'task_items'                    => '修复件',
                'service_item'                  => '维修内容',
                'deliver_nickname'              => '确认送达人姓名',
                'service_nickname'              => '维修人姓名',
                'service_end_nickname'          => '维修完成操作人姓名',
                'return_nickname'               => '还件人姓名',
                'createtime'                    => '创建时间',
                'updatetime'                    => '更新时间',
            ];

            $export = new Export();
            $spreadsheet = null;
            $sheet = null;


            if (count($dataList) == 0) {
                $this->error('导出数据为空');
            }

            $newList = [];
            foreach ($dataList as $row) {
                $arr['id'] = $row['id'];
                $arr['order_sn'] = $row['order_sn'].' ';
                $arr['user_nickname'] = $row['user_nickname'];
                $arr['date'] = $row['date'];
                $arr['models'] = $row['models'];
                $arr['car_number'] = $row['car_number'];
                $arr['province_name'] = $row['province_name'];
                $arr['city_name'] = $row['city_name'];
                $arr['area_name'] = $row['area_name'];
                $arr['address'] = $row['address'];
                $arr['name_4s'] = $row['name_4s'];
                $arr['insurance_company'] = isset($row['insurance_company']['name']) ? $row['insurance_company']['name'] : '-';
                $arr['receptionist'] = $row['receptionist'];
                $arr['pick_nickname'] = $row['pick_nickname'];
                $arr['sure_name'] = $row['sure_name'];
                $arr['return_name'] = isset($row['return']['name']) ? $row['return']['name'] : '-';
                $arr['price'] = $row['price'];
                $arr['status'] = $row['status_text'];
                $arr['remark'] = $row['remark'];
//                $arr['images'] = $row['images'];
                $arr['images'] = '';
                $arr['task_items'] = join(',',$row['task_items']);
                $arr['service_item'] = join(',',TasksService::getItem($row['id']));
                $arr['deliver_nickname'] = $row['deliver_nickname'];
                $arr['service_nickname'] = $row['service_nickname'];
                $arr['service_end_nickname'] = $row['service_end_nickname'];
                $arr['return_nickname'] = $row['return_nickname'];
                $arr['createtime'] = date('Y-m-d H:i:s',$row['createtime']);
                $arr['updatetime'] = date('Y-m-d H:i:s',$row['updatetime']);
                $newList[] = $arr;
            }



            $export->exportExcel('订单列表-' . date('Y-m-d H:i:s'), $expCellName, $newList);

        }
    }


    /*
     * 任务拒接审核
     */
    public function refuse()
    {
        $id = $this->request->post('id');
        $flag = $this->request->post('flag');
        if (!$id || $flag == '') {
            $this->error(__('Invalid parameters'));
        }
        $task = $this->model->where(['id' => $id])->find();
        if (!$task) {
            $this->error(__('No Results were found'));
        }
        if ($task->status != -2){
            $this->error(__('该任务或已经被审核'));
        }
        Db::startTrans();
        try {
            //审核不通过，任务将重新开始倒计时
            if (!$flag){
                $task->curr_flow = 'take';
                $task->status = 0;
                $task->take_status = 0;
                $task->ext = json_encode($task->setExt($task, ['refuse_not_pass_time' => time()]));      // 审核不通过时间
                $task->save();
                //添加任务动作
                TaskAction::operAdd($task,$this->auth->getUserInfo(),'admin','refuse_not_pass',TaskAction::$memo_arr[9]);
                //开始任务倒计时队列
                $data['task'] = $task;
                Hook::listen('task_create_after',$data);
            }else{
                //审核通过，任务变拒绝接单状态
                $task->curr_flow = 'take';
                $task->status = -3;
                $task->take_status = -3;
                $task->ext = json_encode($task->setExt($task, ['refuse_pass_time' => time(),'invalid_time'=>time()]));      // 审核通过时间
                $task->save();
                //添加任务动作
                TaskAction::operAdd($task,$this->auth->getUserInfo(),'admin','refuse_pass',TaskAction::$memo_arr[10]);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error(__($e->getMessage()));
        }
        $this->success('操作成功');
    }


    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = max(0, $this->request->get("offset/d", 0));
        $limit = max(0, $this->request->get("limit/d", 0));
        $limit = $limit ?: 999999;
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = max(0, $this->request->get("page/d", 1));
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = $op[$k] ?? '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper($op[$k] ?? $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            if ($v == 'range_more'){
                $where[] = [$k, '>', 172800];
            }else{
                switch ($sym) {
                    case '=':
                    case '<>':
                        $where[] = [$k, $sym, (string)$v];
                        break;
                    case 'LIKE':
                    case 'NOT LIKE':
                    case 'LIKE %...%':
                    case 'NOT LIKE %...%':
                        $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                        break;
                    case '>':
                    case '>=':
                    case '<':
                    case '<=':
                        $where[] = [$k, $sym, intval($v)];
                        break;
                    case 'FINDIN':
                    case 'FINDINSET':
                    case 'FIND_IN_SET':
                        $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                        $findArr = array_values($v);
                        foreach ($findArr as $idx => $item) {
                            $bindName = "item_" . $index . "_" . $idx;
                            $bind[$bindName] = $item;
                            $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                        }
                        break;
                    case 'IN':
                    case 'IN(...)':
                    case 'NOT IN':
                    case 'NOT IN(...)':
                        $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                        break;
                    case 'BETWEEN':
                    case 'NOT BETWEEN':
                        $arr = array_slice(explode(',', $v), 0, 2);
                        if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                                return $v != '' && $v !== false && $v !== null;
                            })) {
                            continue 2;
                        }
                        //当出现一边为空时改变操作符
                        if ($arr[0] === '') {
                            $sym = $sym == 'BETWEEN' ? '<=' : '>';
                            $arr = $arr[1];
                        } elseif ($arr[1] === '') {
                            $sym = $sym == 'BETWEEN' ? '>=' : '<';
                            $arr = $arr[0];
                        }
                        $where[] = [$k, $sym, $arr];
                        break;
                    case 'RANGE':
                    case 'NOT RANGE':
                        $v = str_replace(' - ', ',', $v);
                        $arr = array_slice(explode(',', $v), 0, 2);
                        if (stripos($v, ',') === false || !array_filter($arr)) {
                            continue 2;
                        }
                        //当出现一边为空时改变操作符
                        if ($arr[0] === '') {
                            $sym = $sym == 'RANGE' ? '<=' : '>';
                            $arr = $arr[1];
                        } elseif ($arr[1] === '') {
                            $sym = $sym == 'RANGE' ? '>=' : '<';
                            $arr = $arr[0];
                        }
                        $tableArr = explode('.', $k);
                        if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias)
                            && !empty($this->model) && $this->relationSearch) {
                            //修复关联模型下时间无法搜索的BUG
                            $relation = Loader::parseName($tableArr[0], 1, false);
                            $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                        }
                        $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                        break;
                    case 'NULL':
                    case 'IS NULL':
                    case 'NOT NULL':
                    case 'IS NOT NULL':
                        $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                        break;
                    default:
                        break;
                }
            }

            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

}
